from threading import *
from random import randint
from time import sleep

lock = Lock()
done = Condition()

num = 30
numOfItem = 100

def loop(ID):
    global num
    lock.acquire()
    print str(ID) + ' thread starting....\n'
    t = randint(1, 10)
    print str(t) + '\n'
    lock.release() 

    
    sleep(t)
    lock.acquire()
    print str(ID) + ' thread stoped\n'
    lock.release()
    
    done.acquire()
    done.notify()
    num += 1
    done.release()


threads = []
for i in range(numOfItem):
    t = Thread(target=loop, args=(i,))
    threads.append(t)

for i in range(numOfItem):
    if num > 0:
        lock.acquire()
        num -= 1
        print 'num: ' + str(num)
        lock.release()
    else:
        done.acquire()
        done.wait()
        done.release()

    threads[i].start()

for i in range(numOfItem):
    threads[i].join()
    print str(i)+ '***'
